using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;
using Comteck.Dto.Users;
using Comteck.Ktt.Services.Users;
using Comteck.Localization;
using Comteck.Security;
using Comteck.Winforms;
using Comteck.Winforms.Utils;
using Microsoft.Extensions.DependencyInjection;

namespace Comteck.Ktt.Base {
  /// <summary>
  /// 登录界面
  /// </summary>
  public partial class FrmLogin : FrmSkinBase {
    [DllImport("user32.dll", SetLastError = true)]
    private static extern int SetWindowRgn(IntPtr hWnd, IntPtr hRgn, bool bRedraw);

    [DllImport("gdi32.dll")]
    private static extern IntPtr CreateRoundRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect, int nWidthEllipse, int nHeightEllipse);

    private LoginUserDto entityModel;

    private readonly IUserService _userService;

    public FrmLogin(IUserService userService) {
      _userService = userService;
      InitializeComponent();
      SetFormRoundCorners();
    }

    private void SetFormRoundCorners() {
      int radius = 16; // 圆角半径
      IntPtr hRgn = CreateRoundRectRgn(0, 0, this.Width, this.Height, radius, radius);
      SetWindowRgn(this.Handle, hRgn, true); // 设置窗体的区域为圆角
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void FrmLogin_Load(object sender, EventArgs e) {
      if (this.DesignMode) {
        return;
      }

      // 关闭加载动画效果
      WinformHelper.CloseLoadScreen();

      // 激活窗口
      this.Activate();

      // 添加拖动事件
      this.AddDragEvents();
      labelControl4.AddDragEvents();

      // 重新设置httpclient
      //SysGlobal.InitHttpClient();

      this.InitLoginModel();

      // 记住焦点
      if (ckUserId.EditValue.Is(EnumValidateType.Null)) {
        ckUserId.FocusAndSelectAll();
      } else {
        ckPassword.FocusAndSelectAll();
      }
    }
    /// <summary>
    /// 
    /// </summary>
    private void InitLoginModel() {
      entityModel = new LoginUserDto();
      mvvmContext1.BindForm(entityModel, dxValidationProvider1);
    }

    private async void ckPassword_KeyDown(object sender, KeyEventArgs e) {
      if (e.KeyCode == Keys.Enter) {
        e.Handled = true;
        await this.CheckLoginAsync();
      }
    }

    private async void BtnLogin_KeyDown(object sender, KeyEventArgs e) {
      if (e.KeyCode == Keys.Enter) {
        e.Handled = true;
        await this.CheckLoginAsync();
      }
    }

    private async void BtnLogin_MouseClick(object sender, MouseEventArgs e) {
      if (e.Button == MouseButtons.Left) {
        await this.CheckLoginAsync();
      }
    }
    /// <summary>
    /// 
    /// </summary>
    private async Task CheckLoginAsync() {
      // 这个地方特殊，需要check是否在登录中
      if (ajaxLoad.IsWork()) {
        return;
      }

      // 验证不通过
      if (!dxValidationProvider1.Validate()) {
        return;
      }

      // rsa加密
      entityModel.Password = entityModel.Password ?? string.Empty;
      var password = entityModel.Password.TrimSafe();
      entityModel.Password = SecurityFactory.GetSecurity("MD5").Encrypt(entityModel.Password, null);
      Logger.Info($"password = {entityModel.Password}");

      // 校验用户License

      #region 登录系统

      // submit
      ajaxLoad.Show();
      var userResult = await _userService.AuthenticateAsync(entityModel);
      ajaxLoad.Hide();

      if (userResult.Code != 1) {
        entityModel.Password = password;
        this.ShowMsg(BaseResources.Login_Faild, userResult.Message);
        return;
      }

      #endregion

      // 保存登录信息
      SysGlobal.LoginUser = userResult.Data;

      // 隐藏
      this.Hide();

      // 打开主界面，必须使用showdialog
      SysGlobal.MainForm = SysGlobal.ServiceProvider.GetRequiredService<FrmMain>();
      SysGlobal.MainForm.ShowDialog();

      // 关闭本窗体
      this.Close();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void BtnCancel_KeyDown(object sender, KeyEventArgs e) {
      if (e.KeyCode == Keys.Enter) {
        SysGlobal.Close();
      }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void BtnCancel_MouseClick(object sender, MouseEventArgs e) {
      if (e.Button == MouseButtons.Left) {
        SysGlobal.Close();
      }
    }
  }
}
